package com.itcast.demo.mybatisinterceptor.interceptor;


import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.util.Map;
import java.util.Properties;
// 如果项目中使用了pageHelper等分页插件，这里的拦截逻辑可能需要调整以适配分页插件的实现方式。
// https://mp.weixin.qq.com/s/4w3TNC6DEX_L_GvZJVeJqA
@Component
@Intercepts({
        @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
})
public class PaginationInterceptor implements Interceptor {

    private static final int MAX_LIMIT = 1000;


    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        // 获取boundSql对象
        BoundSql boundSql = statementHandler.getBoundSql();
        // 获取SQL语句
        String sql = boundSql.getSql();

        // 检查分页参数，这里假设分页参数是通过BoundSql的parameterMappings来传递的
        // 实际项目中可能需要根据具体的分页插件或自定义实现来调整这部分逻辑
        Object parameterObject = boundSql.getParameterObject();
        if (parameterObject instanceof Map) {
            Map<String, Object> parameterMap = (Map<String, Object>) parameterObject;
            if (parameterMap.containsKey("limit")) {
                Integer limit = (Integer) parameterMap.get("limit");
                if (limit > MAX_LIMIT) {
                    parameterMap.put("limit", MAX_LIMIT);
                }
            }
        }

        // 继续执行下一个拦截器或目标方法
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // 可以在这里配置拦截器的属性
    }
}
